﻿using System;
using Ease.EaseNode.Runtime.Param;
using Unity.Collections;
using UnityEngine;

namespace Ease.EaseNode.Runtime
{
    public partial class BaseEaseNodeData
    {
#if UNITY_EDITOR
        public abstract string Key { get; }

        [SerializeField] [ReadOnly] protected CommonEaseNodeInfo nodeInfo = new CommonEaseNodeInfo();

        public IEaseNodeInfo NodeInfo
        {
            get
            {
                if (nodeInfo == null)
                {
                    nodeInfo = new CommonEaseNodeInfo();
                }

                return nodeInfo;
            }
        }

        protected virtual void CreateNodeInfo()
        {
            NodeInfo.Key = this.Key;
            NodeInfo.OnInit -= OnNodeInfoInit;
            NodeInfo.OnInit += OnNodeInfoInit;
            NodeInfo.OnChange -= OnNodeInfoChange;
            NodeInfo.OnChange += OnNodeInfoChange;
        }

        protected abstract void OnNodeInfoInit();
        protected abstract void OnNodeInfoChange();
        protected IEaseNodeDataState State { get; set; }

        public IEaseNodeDataState CreateState()
        {
            CreateNodeInfo();
            if (State == null)
            {
                State = OnCreateState();
                StateManager.Add(State);
            }

            return State;
        }

        protected virtual IEaseNodeDataState OnCreateState()
        {
            return new CommonEaseNodeDataState(this);
        }

        public virtual void OnCreate()
        {
        }

        public virtual void OnDestroy()
        {
            if (Agent != null)
                Agent.OnValueChangeEvent -= OnValueChange;
        }

        public event Action<BaseChangeParam> OnValueChangeEvent;

        public void OnValueChange(BaseChangeParam param)
        {
            State?.OnValueChange(param);
        }
#endif
    }
}